from sqlmodel import Session, select, and_, or_, func
from fastapi import Query
from typing import Annotated, Optional
import models
import utility
from common import exception
from datetime import datetime
from dependencies import engine, SessionDep

"""查询字典列表数据

Keyword arguments:
skip -- 起始页 (default 0)
limit -- 每页条数 (default 20)
id -- 字典ID (default None)
name -- 字典名称 (default None)
code -- 字典编码 (default None)
type -- 字典类型 (default None)
type_code -- 字典类型编码 (default None)
Return: 字典列表数据
"""


def get_dict(
    skip: int = 0,
    limit: Annotated[int, Query(le=100)] = 100,
    name: str | None = None,
    code: int | None = None,
    type: str | None = None,
    type_code: str | None = None,
    user: models.SystemUser = None,
    session: SessionDep = Session(engine),
):
    try:
        # 查询条件
        conditions = [
            models.SystemDict.name.like(f"%{name}%") if name else True,
            models.SystemDict.code == code if code is not None else True,
            models.SystemDict.type.like(f"%{type}%") if type else True,
            models.SystemDict.type_code == type_code if type_code is not None else True,
        ]

        statement = (
            select(models.SystemDict)
            .filter(and_(*conditions))
            .order_by(models.SystemDict.updatetime.desc())
            .offset(skip)
            .limit(limit)
        )

        # 执行查询
        items = session.exec(statement).all()

        # 查询总条数
        total_statement = (
            select(func.count())
            .select_from(models.SystemDict)
            .filter(and_(*conditions))
        )
        total = session.exec(total_statement).one()  # 使用 one() 方法获取单个标量结果

        # 将创建人和更新人的ID转换为姓名
        system_dict = utility.general.convert_id_to_name(items=items, session=session)

        return system_dict, total
    except Exception as e:
        session.rollback()
        raise e


"""新增字典数据

Keyword arguments:
dict -- 新增字典数据
Return: 新增字典数据
"""


def create_dict(
    dic: models.SystemDictBase,
    user: models.SystemUser = None,
    session: SessionDep = Session(engine),
):
    # 新增字典数据
    system_dict = models.SystemDict(
        **dict(dic),
        create_id=user.id,
        update_id=user.id,
        createtime=datetime.now(),
        updatetime=datetime.now(),
    )
    session.add(system_dict)
    session.commit()
    session.refresh(system_dict)
    return system_dict


"""编辑字典数据

Keyword arguments:
id -- 字典ID
dict -- 编辑字典数据
Return: 新增字典数据
"""


def update_dict(
    id: int,
    dict: models.SystemDictBase,
    user: models.SystemUser = None,
    session: SessionDep = Session(engine),
):
    # 查询字典数据
    system_dict = session.get(models.SystemDict, id)

    # 如果字典数据不存在，则抛出异常
    if not system_dict:
        raise exception.create_http_exception(status_code=404, detail="字典数据不存在")

    # 更新字典数据
    system_dict.name = dict.name
    system_dict.code = dict.code
    system_dict.type = dict.type
    system_dict.type_code = dict.type_code
    system_dict.update_id = user.id
    system_dict.updatetime = datetime.now()
    session.commit()
    session.refresh(system_dict)
    return system_dict


"""删除字典数据

Keyword arguments:
id -- 字典id 
Return: None
"""


def delete_dict(
    id: int, user: models.SystemUser = None, session: SessionDep = Session(engine)
):
    # 查询字典数据
    system_dict = session.get(models.SystemDict, id)

    # 如果字典数据不存在，则抛出异常
    if not system_dict:
        raise exception.create_http_exception(status_code=404, detail="字典数据不存在")

    # 删除字典数据
    session.delete(system_dict)
    session.commit()
